Function Declaration and Expression

In JavaScript, there are two main ways to define a function: function declaration and function expression.

Function Declaration

Function declarations are hoisted to the top of their scope, which means they can be called before they are declared in the code.

function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!

Function Expression

Function expressions are not hoisted, and they can be anonymous or named. They are often assigned to variables or used as arguments for other functions.

const multiply = function(a, b) {
return a * b;
};
console.log(multiply(3, 4)); // Output: 12

Parameters and Arguments

Functions can accept input values called parameters, and the actual values passed to the function when it's called are called arguments.

function sum(a, b) { // a and b are parameters
return a + b;
}
console.log(sum(2, 3)); // 2 and 3 are arguments
// Output: 5

 

Return Statement

The return statement is used to return a value from a function. If no value is specified, the function will return undefined.

function square(num) {
return num * num;
}
console.log(square(5)); // Output: 25

Scope and Closures

In JavaScript, variables have different scopes based on where they are declared. There are two types of scope: global scope and local scope (function scope and block scope).

Closures are functions that have access to variables from an outer (enclosing) function, even after the outer function has finished executing.

function outerFunction() {
const outerVar = "I am outside!";
function innerFunction() {
console.log(outerVar); // Accessible due to closure
}
return innerFunction;
}
const myInnerFunc = outerFunction();
myInnerFunc(); // Output: I am outside!

Arrow Functions

Arrow functions, introduced in ES6, provide a more concise syntax for defining functions. They also have lexical this binding, meaning that the value of this inside an arrow function is determined by the surrounding lexical scope.

const square = (num) => {
return num * num;
};
console.log(square(5)); // Output: 25

In the next chapter, we'll explore arrays, which are data structures used to store collections of values in JavaScript.